#!/bin/bash
#
# This script generates all protobuf files using the embedded version of
# Protobuf. It is important that the version used to generate the files is the
# same version being linked.
#
# You only need to run this if you change a .proto file or update the Protobuf
# submodule.
#

set -e

# This script works in both Docker and normal build environments.
# Protobuf and co. tools are taken from: $PREFIX if provided, or from $PWD/build/local if exists, or from /usr/bin
if [ -z $PREFIX ]
then
    # PREFIX not set
    ROOT="$PWD"
    PREFIX="$ROOT/build/local"
    if  [ ! -d $PREFIX ] || \
        [ ! -d $PREFIX/include ] || \
        [ ! -f $PREFIX/bin/protoc ] || \
        [ ! -f $PREFIX/bin/protoc-gen-c-typedef ]
    then
        echo $PREFIX does not exist or not complete, fallback to /usr/local
        PREFIX=/usr/local
    fi
fi
echo "PREFIX: $PREFIX"
export PATH="$PREFIX/bin":$PATH
# library paths, for protobuf plugins
export LD_LIBRARY_PATH="$PREFIX/lib":$LD_LIBRARY_PATH
export DYLD_LIBRARY_PATH="$PREFIX/lib":$LD_LIBRARY_PATH
# protoc executable (protobuf compiler)
PROTOC="$PREFIX/bin/protoc"
which $PROTOC
$PROTOC --version

# Clean
rm -rf swift/Sources/Generated
rm -rf jni/java/wallet/core/jni
rm -rf jni/cpp/generated

mkdir -p swift/Sources/Generated/Protobuf swift/Sources/Generated/Enums

# Generate coins info from registry.json
codegen/bin/coins

# Generate interface code
codegen/bin/codegen

# Generate Java, C++ and Swift Protobuf files
if [ -x "$(command -v protoc-gen-swift)" ]; then
    "$PROTOC" -I=$PREFIX/include -I=src/proto --cpp_out=src/proto --java_out=lite:jni/java --swift_out=swift/Sources/Generated/Protobuf --swift_opt=Visibility=Public src/proto/*.proto
else
    "$PROTOC" -I=$PREFIX/include -I=src/proto --cpp_out=src/proto --java_out=lite:jni/java src/proto/*.proto
fi

# Generate internal message protocol Protobuf files
"$PROTOC" -I=$PREFIX/include -I=src/Tron/Protobuf --cpp_out=src/Tron/Protobuf src/Tron/Protobuf/*.proto
"$PROTOC" -I=$PREFIX/include -I=src/Zilliqa/Protobuf --cpp_out=src/Zilliqa/Protobuf src/Zilliqa/Protobuf/*.proto
"$PROTOC" -I=$PREFIX/include -I=src/Cosmos/Protobuf --cpp_out=src/Cosmos/Protobuf src/Cosmos/Protobuf/*.proto
"$PROTOC" -I=$PREFIX/include -I=tests/Cosmos/Protobuf --cpp_out=tests/Cosmos/Protobuf tests/Cosmos/Protobuf/*.proto

# Generate Proto interface file
"$PROTOC" -I=$PREFIX/include -I=src/proto --plugin=$PREFIX/bin/protoc-gen-c-typedef --c-typedef_out include/TrustWalletCore src/proto/*.proto
"$PROTOC" -I=$PREFIX/include -I=src/proto --plugin=$PREFIX/bin/protoc-gen-swift-typealias --swift-typealias_out swift/Sources/Generated/Protobuf src/proto/*.proto

# Generate Xcode project
if [ -x "$(command -v xcodegen)" ]; then
    pushd swift
    xcodegen
    pod install
    popd
else
    echo -e "\nWARNING: Skipped generating Xcode project because the xcodegen tool is not installed."
fi
